console.log('RUNNING COMMENT JAVASCRIPT');
/**
 * Temporary GTParking JSON. Currently (04-13-12) GTPlaces does not have
 * these visitor parking locations on record so I'm making my own in
 * accordance with the GTPlaces json structure
 * @author Daranhdara Hun
 */
var gtplacesjson = [{
	"b_id" : "10000",
	"name" : "Student Center Visitor Parking",
	"address" : "350 Ferst Drive",
	"image_url" : "",
	"latitude" : "33.773520",
	"longitude" : "-84.399285",
	"phone_num" : "(404) 894-2788",
	"tag_list" : ["student center", "student center parking", "parking"]
}, {
	"b_id" : "10001",
	"name" : "Howey Physics Visitor Parking",
	"address" : "Ferst Dr. NW/State St NW",
	"image_url" : "",
	"latitude" : "33.778006",
	"longitude" : "-84.399076",
	"phone_num" : "(404) XXX-XXXX",
	"tag_list" : ["Nano Building Parking", "nano technology", "coc", "College of computing", "Howey Physics Building Parking"]
}, {
	"b_id" : "10002",
	"name" : "Technology Square Visitor Parking",
	"address" : " 800 Spring St NW, Georgia Institute of Technology",
	"image_url" : "",
	"latitude" : "33.776204",
	"longitude" : "-84.388937",
	"phone_num" : "(404) XXX-XXXX",
	"tag_list" : ["Tech Square", "Barnes and Nobles", "Parking"]
}];
/**********************************************************************************************/
/**********************************************************************************************/
/* Below are library of helper functions */
/**********************************************************************************************/
/**********************************************************************************************/
/**
 * get current location and sort parking lots by locations
 * @author Wai Chip Ngai
 */
function sortByDistance(position)
            {
            var lat = position.coords.latitude;
            var lng = position.coords.longitude;
            alert("Current position: \n" + "Latitude: "+lat + "\nLongitude: " + lng);
            var location = lat+","+lng;
            //Remove the old rows
			$(".plot_row").remove();
			//JQuery Fetch The New Ones
			$.ajax({
				url : "api/sortdist/",
				dataType : "json",
				async : false,
				data:{'location':location},
				type:'POST',
				success : function(data, textStatus, jqXHR) {
					console.log(data);
					//Create The New Rows From Template
					$('#plot_list').data('plot_list', data);
					$("#plot_template").tmpl(data).appendTo("#plot_list");
				},
				error : ajaxError
			});

			$('#plot_list').listview('refresh');
            }
/**********************************************************************************************/
/**********************************************************************************************/
/* Below is Main initialization function */
/**********************************************************************************************/
/**********************************************************************************************/
/**
 * Initialization function
 * Sets up the Parking home page with information
 * Gathers information from server of all available visitor parking lots
 * @author Daranhdara Hun
 */             
$(function() {
	// Handler for .ready() called.
	console.log('ready to run');

	// Get list of parking lots
	$('#list_parking_lots').bind('pagebeforeshow', function(event, ui) {
		console.log('Listing Parking lots');

		//Remove the old rows
		$(".plot_row").remove();

		//JQuery Fetch The New Ones
		$.ajax({
			url : "api/lots",
			dataType : "json",
			async : false,
			success : function(data, textStatus, jqXHR) {
				console.log(data);
				//Create The New Rows From Template
				$('#plot_list').data('plot_list', data);
				$("#plot_template").tmpl(data).appendTo("#plot_list");
			},
			error : ajaxError
		});

		$('#plot_list').listview('refresh');
	});
	// Sorts lots by availability
	$('#availBtn').bind('click', function(event, ui) {
		console.log('Sorting lots by availability');

		//Remove the old rows
		$(".plot_row").remove();

		//JQuery Fetch The New Ones
		$.ajax({
			url : "api/sortavail/",
			dataType : "json",
			async : false,
			success : function(data, textStatus, jqXHR) {
				console.log(data);
				//Create The New Rows From Template
				$('#plot_list').data('plot_list', data);
				$("#plot_template").tmpl(data).appendTo("#plot_list");
			},
			error : ajaxError
		});

		$('#plot_list').listview('refresh');
	});
	
	//Prompt for directions
	$('#directBtn').bind('click', function(event, ui) {
		console.log('Asking system for directions to specified lot');
	
		//JQuery fetch the lat/long of specified id.
		$.ajax({
			url : "api/lots/" + b_id,
			dataType : "json",
			async : false,
			success : function(data, textStatus, jqXHR) {
				if(navigator.geolocation)
               		currentPosition = navigator.geolocation.getCurrentPosition();
               		calcRoute(currentPosition, data);
            	else
               		alert("navigator.geolocation is not available");
			},
			error : ajaxError
		});
	});
	
	
	// Sorts lots by distance
	$('#distBtn').bind('click', function(event, ui) {
		console.log('Sorting lots by distance');
		    if(navigator.geolocation)
               navigator.geolocation.getCurrentPosition(sortByDistance);
            else
                alert("navigator.geolocation is not available");
	});

	$('#plot_3').bind('click', function(event, ui) {
		console.log('Parking Lot Information Rendered');
		var myOptions = {
			center : new google.maps.LatLng(33.777644, -84.400535),
			zoom : 14,
			mapTypeId : google.maps.MapTypeId.ROADMAP
		};

		var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
		var id = $.url().fparam("plotID");
		var name = $.url().fparam("plotName");
		//Remove the old rows
		$(".plot_info").remove();
		//Retrieve the saved json
		var mydata = $('#plot_list').data('plot_list');
		var length = mydata.length;
		var i = 0;
		for( i = 0; i < length; i++) {
			if(mydata[i].id_pk == id) {
				$( "#plot_info_template" ).mydata[i].appendTo("#list_a_lots_information");
				$('#list_a_lots_information').listview('refresh');
				break;
			}
		}

	});
	// Goes in and updates each list tag with the gtplaces tags
	$('#plot_list').ready(function() {
		$.ajax({
			url : "http://m.cip.gatech.edu/api/gtplaces/buildings_tags",
			dataType : "json",
			async : false,
			success : function(data, textStatus, jqXHR) {
				console.log(data);
				console.log(gtplacesjson);
				//ALL THE gtplacesjson's need to be replaced with 'data' after the gtplaces api is fixed
				var size = gtplacesjson.length;
				var i, j;
				for( i = 0; i < size; i++) {
					// get the id
					var id = gtplacesjson[i].b_id;
					var tagid = "#parkinglot_" + id;
					var tags = gtplacesjson[i].tag_list;
					var tags_size = tags.length;
					var tags_str = "";
					for( j = 0; j < tags_size; j++) {
						tags_str += tags[j];
						tags_str += " ";
					}
					$(tagid).attr('data-filtertext', tags_str);
				}
			},
			error : ajaxError
		});
	});
});
/******************************************************************************/

function ajaxError(jqXHR, textStatus, errorThrown) {
	console.log('ajaxError ' + textStatus + ' ' + errorThrown);
	$('#error_message').remove();
	$("#error_message_template").tmpl({
		errorName : textStatus,
		errorDescription : errorThrown
	}).appendTo("#error_dialog_content");
	$.mobile.changePage($('#error_dialog'), {
		transition : "pop",
		reverse : false,
		changeHash : false
	});
}

/******************************************************************************/